package library;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.URI;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.ProtocolException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultRedirectHandler;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HttpContext;

import android.util.Log;

public class YonseiAuthorizer
{
  public static final String FAKE_USER_AGENT = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.0 (KHTML, like Gecko) Chrome/6.0.408.1 Safari/534.0";
  private boolean mAuthorized;
  private HttpClient mClient;
  private String mToken;

  public void authorize(String id, String pw)
  {
    this.mAuthorized = false;
    try
    {
      DefaultHttpClient localDefaultHttpClient = getNewHttpClient();
      localDefaultHttpClient.setRedirectHandler(new RedirectHandler());
      
      this.mClient = localDefaultHttpClient;
      HttpGet localHttpGet1 = new HttpGet("https://underwood1.yonsei.ac.kr/haksa/sso/main.jsp");
      
      localHttpGet1.setHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.0 (KHTML, like Gecko) Chrome/6.0.408.1 Safari/534.0");
      BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(this.mClient.execute(localHttpGet1).getEntity().getContent()));
      
      while (true)
      {
        String str = localBufferedReader.readLine();
        if (str == null)
        {
          localBufferedReader.close();
          if (this.mToken != null)
            break;
          return;
        }
        int i = str.indexOf("site2pstoretoken\" value=\"");
        if (i < 0)
          continue;
        this.mToken = str.substring(i + "site2pstoretoken\" value=\"".length(), str.lastIndexOf('"'));
      }
    }
    catch (IOException localIOException)
    {
    	Log.d("ERROR", localIOException.toString());
    	return;
    }
  
    try {
        HttpGet localHttpGet2 = new HttpGet("https://im.yonsei.ac.kr/sso/auth?v=v1.2&site2pstoretoken=" + this.mToken + "&ssousername=" + id + "&password=" + pw + "&locale=");
		this.mClient.execute(localHttpGet2);
	} catch (ClientProtocolException e) {
		// TODO Auto-generated catch block
    	Log.d("ERROR", e.toString());
	} catch (IOException e) {
		// TODO Auto-generated catch block
    	Log.d("ERROR", e.toString());
	}
  }
  

  public HttpClient getAuthorizedHttpClient()
  {
    return this.mClient;
  }

  public String getToken()
  {
    return this.mToken;
  }

  public boolean isAuthorized()
  {
    return this.mAuthorized;
  }

  private class RedirectHandler extends DefaultRedirectHandler
  {
    private RedirectHandler()
    {
    
    }

    public URI getLocationURI(HttpResponse paramHttpResponse, HttpContext paramHttpContext)
      throws ProtocolException
    {
      URI localURI = super.getLocationURI(paramHttpResponse, paramHttpContext);
      if (localURI.toString().contains("osso_login_success"))
        YonseiAuthorizer.this.mAuthorized = true;
      return localURI;
    }
  }
  
  public static DefaultHttpClient getNewHttpClient()
  {
    try
    {
    	
      KeyStore localKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
      localKeyStore.load(null, null);
      EasySSLSocketFactory localEasySSLSocketFactory = new EasySSLSocketFactory(localKeyStore);
      localEasySSLSocketFactory.setHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
      BasicHttpParams localBasicHttpParams = new BasicHttpParams();
      HttpProtocolParams.setVersion(localBasicHttpParams, HttpVersion.HTTP_1_1);
      HttpProtocolParams.setContentCharset(localBasicHttpParams, "UTF-8");
      SchemeRegistry localSchemeRegistry = new SchemeRegistry();
      
      localSchemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
      
      localSchemeRegistry.register(new Scheme("https", localEasySSLSocketFactory, 443));
      
      DefaultHttpClient localDefaultHttpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(localBasicHttpParams, localSchemeRegistry), localBasicHttpParams);
     
      return localDefaultHttpClient;
    }catch (Exception localException)
    {
    	Log.d("ERROR", localException.toString());
    }
	return null;	
  }

  public static class EasySSLSocketFactory extends org.apache.http.conn.ssl.SSLSocketFactory
  {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    private X509TrustManager local1;
    
    
    public EasySSLSocketFactory(KeyStore paramKeyStore)
      throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException
    {
       super(paramKeyStore);
       local1 = new X509TrustManager()
      {
        public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
          throws CertificateException
        {
        }

        public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
          throws CertificateException
        {
        }

        public X509Certificate[] getAcceptedIssuers()
        {
          return null;
        }
      };
      SSLContext localSSLContext = this.sslContext;
      TrustManager[] arrayOfTrustManager = new TrustManager[1];
      arrayOfTrustManager[0] = local1;
      localSSLContext.init(null, arrayOfTrustManager, null);
    }

    public Socket createSocket()
      throws IOException
    {
      return this.sslContext.getSocketFactory().createSocket();
    }

    public Socket createSocket(Socket paramSocket, String paramString, int paramInt, boolean paramBoolean)
      throws IOException, UnknownHostException
    {
      SSLSocket localSSLSocket = (SSLSocket)this.sslContext.getSocketFactory().createSocket(paramSocket, paramString, paramInt, paramBoolean);
      String[] arrayOfString = new String[1];
      arrayOfString[0] = "SSLv3";
      localSSLSocket.setEnabledProtocols(arrayOfString);
      return localSSLSocket;
    }
  }
}